package com.alibaba.citrus.ots.platform.enhance.functions.inventoryAllot.entity;

import com.alibaba.citrus.ots.common.util.SpringContextUtil;
import com.alibaba.citrus.ots.platform.enhance.repository.InventoryAllotLineRepository;
import com.alibaba.citrus.ots.platform.enhance.repository.InventoryAllotRepository;
import com.epoch.app.otsplatformenhance.model.dto.InventoryAllotLineSDO;
import com.epoch.app.otsplatformenhance.model.dto.InventoryAllotSDO;
import lombok.Data;
import org.springframework.transaction.annotation.Transactional;

@Data
public class InventoryAllotEntity {

    private InventoryAllotSDO inventoryAllotSDO;

    private static InventoryAllotRepository inventoryAllotRepository;
    private static InventoryAllotLineRepository inventoryAllotLineRepository;

    static {
        inventoryAllotRepository = SpringContextUtil.getBean(InventoryAllotRepository.class);
        inventoryAllotLineRepository = SpringContextUtil.getBean(InventoryAllotLineRepository.class);
    }

    public static InventoryAllotEntity of(InventoryAllotSDO inventoryAllotSDO) {
        InventoryAllotEntity inventoryAllotEntity = new InventoryAllotEntity();
        inventoryAllotEntity.inventoryAllotSDO = inventoryAllotSDO;
        return inventoryAllotEntity;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public void create() {
        String s = inventoryAllotRepository.create(inventoryAllotSDO);
        for (InventoryAllotLineSDO inventoryAllotLineSDO : inventoryAllotSDO.getInventoryAllotLineSDOS()) {
            inventoryAllotLineSDO.setInventoryAllotId(s);
            inventoryAllotLineRepository.create(inventoryAllotLineSDO);
        }
    }

    public void excelImport() {
        if (inventoryAllotSDO.getId() != null) {
            inventoryAllotRepository.update(inventoryAllotSDO);
            for (InventoryAllotLineSDO inventoryAllotLineSDO : inventoryAllotSDO.getInventoryAllotLineSDOS()) {
                inventoryAllotLineRepository.update(inventoryAllotLineSDO);
            }
            return;
        }
        String s = inventoryAllotRepository.create(inventoryAllotSDO);
        for (InventoryAllotLineSDO inventoryAllotLineSDO : inventoryAllotSDO.getInventoryAllotLineSDOS()) {
            inventoryAllotLineSDO.setInventoryAllotId(s);
            inventoryAllotLineRepository.create(inventoryAllotLineSDO);
        }
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public void createInventoryAllotModel() {
        String s = inventoryAllotRepository.create(inventoryAllotSDO);
        for (InventoryAllotLineSDO inventoryAllotLineSDO : inventoryAllotSDO.getInventoryAllotLineSDOS()) {
            inventoryAllotLineSDO.setInventoryAllotId(s);
            inventoryAllotLineRepository.create(inventoryAllotLineSDO);
        }
    }

    public void delete() {
        inventoryAllotRepository.delete(inventoryAllotSDO);
    }
}
